<?php

namespace app\uniapp\controller;

use app\common\exception\MiException;
use app\model\Sign;
use app\model\SignLog;
use app\uniapp\middleware\CheckLogin;
use app\uniapp\service\SignLogService;
use app\uniapp\service\SignService;
use app\uniapp\service\UniAuthService;
use app\uniapp\service\UserPointsLogService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 签到
 */
class UserSignController extends UniController
{
    protected array $middleware = [
        CheckLogin::class,
    ];

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function index(): \think\response\Json
    {
        $uid = UniAuthService::instance()->getLoginId();
        // 最后一次签到记录
        $signLog = SignLog::where('user_id', $uid)->order("create_time desc")->limit(1)->find();
        $signDay = 0; // 已连续签到天数
        $isTodaySign = 0; // 今日是否已签到    // 0-未签到 1-已签到
        $totalSignDay = 0;  // 累计签到天数
        if($signLog){
            $totalSignDay = SignLogService::instance()->setWhere([['user_id', '=',$uid]])->query()->count();
            $lastDay = (int)date('Ymd', $signLog->getData('create_time'));
            $today = (int)date('Ymd', time());
            $diff = $today - $lastDay;  // 上次签到距离现在的天数
            if ($diff == 0) {   // 今天已签到
                $isTodaySign = 1;
                $signDay = $signLog->day;
            }elseif($diff==1){  // 连续签到
                $signDay = $signLog->day;
            }else{  // 非连续签到
                $signDay = 0;
            }
        }
        // 签到配置
        $signs = SignService::instance()->setOrder('sort desc')->select();

        return jsonSuccess([
            'signs' => $signs,
            'signDay' => $signDay,
            'isTodaySign' => $isTodaySign,
            'totalSignDay' => $totalSignDay,
        ]);
    }

    /**
     * 签到
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function doSign(): \think\response\Json
    {
        // 签到
        // 读取上一次签到
        $uid = UniAuthService::instance()->getLoginId();
        $signLog = SignLog::where('user_id', $uid)->order("create_time desc")->limit(1)->find();
        $signs = SignService::instance()->setOrder('sort desc')->select();

        // 设置默认的签到数据为第一天签到
        $data = [
            'user_id' => $uid,
            'points' => $signs[0]->points,
            'day' => 1,
        ];
        if ($signLog){
            // 判断是否连续签到
            $lastDay = (int)date('Ymd', $signLog->getData('create_time'));
            $today = (int)date('Ymd', time());
            $diff = $today - $lastDay;
            $signDay = $signLog->day;   // 连续签到天数
            if ($diff == 0) {   // 同一天不能签到两次
                return jsonError("今天已经签过到了");
            }

            if ($diff==1){    // 连续签到
                if($signDay < 7){   // 连续签到天数小于7天
                    $data['day'] = $signDay+1;  // 追加签到天数
                    $data['points'] = $signs[$signDay+1]->points;
                }else{  // 一周签到结束，重新开始，使用默认数据
                    //
                }

            }else{  // 签到中断，使用默认数据

            }
        }

        SignLogService::instance()->create($data);

        // 创建积分明细
        UserPointsLogService::instance()->create([
            'user_id' => $uid,
            'change_type' => 4, // 签到赠送
            'amount' => $data['points'],
            'note' => '签到赠送',
        ]);
        return jsonSuccess();
    }

}
